package cn.wowjoy.office.loginnew;


import android.annotation.SuppressLint;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.MainThread;
import android.support.annotation.Nullable;
import android.support.annotation.WorkerThread;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import junit.framework.Test;

import java.util.List;
import java.util.regex.Pattern;

import javax.inject.Inject;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.baselivedata.appbase.NewMainApplication;
import cn.wowjoy.office.baselivedata.di.DaggerAppComponent;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.common.widget.MyToast;
import cn.wowjoy.office.data.response.LoginInfo;
import cn.wowjoy.office.data.response.StaffListResponse;
import cn.wowjoy.office.data.response.StaffResponse;
import cn.wowjoy.office.data.room.dao.UserDao;
import cn.wowjoy.office.data.room.entity.UserInfo;
import cn.wowjoy.office.databinding.ActivityLogin2Binding;
import cn.wowjoy.office.main.MainActivity;
import cn.wowjoy.office.utils.PreferenceManager;
import cn.wowjoy.office.utils.dialog.DialogUtils;

public class LoginActivity extends NewBaseActivity<ActivityLogin2Binding,LoginViewModel> {

    @Inject
    UserDao userDao;
    private MDialog waitDialog;
    private MDialog mDG;
    private boolean isVisible = false;

    @WorkerThread
    private void saveUserInfo(String name, String pw){
        UserInfo userInfo = new UserInfo();
        userInfo.setPhone(name);
        userInfo.setPassword(pw);
        userDao.saveUser(userInfo);

    }

    /**
     * 操作数据库需要在后台操作
     * @param name
     * @param pw
     */
    @SuppressLint("StaticFieldLeak")
    @MainThread
    private void saveResultAndReInit(String name, String pw) {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... voids) {
                saveUserInfo(name,pw);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
            }
        }.execute();
    }

    @MainThread
    private void initUserInfo() {
        userDao.loadUsers()
                .observe(LoginActivity.this, new Observer<List<UserInfo>>() {
                    @Override
                    public void onChanged(@Nullable List<UserInfo> userInfos) {
                        if (userInfos == null || userInfos.size() <= 0)
                            return;
                        binding.include1.loginid.setText(userInfos.get(userInfos.size() - 1).getPhone());
                        binding.include1.loginpsw.setText(userInfos.get(userInfos.size() - 1).getPassword());
                    }
                });

    }
    @Override
    protected Class<LoginViewModel> getViewModel() {
        return LoginViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login2;
    }


    @Override
    protected void init(Bundle savedInstanceState) {
        goToMain();
        setStatusBarVisible(false);
        binding.setViewModel(viewModel);
        initUserInfo();

        binding.include1.loginpsw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                binding.include1.delete.setVisibility(TextUtils.isEmpty(binding.include1.loginpsw.getText())?  View.GONE : View.VISIBLE);

            }
        });
        binding.include1.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.include1.loginpsw.setText("");
            }
        });
        binding.include1.showHidePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isVisible){
                    binding.include1.showHidePassword.setImageResource(R.drawable.password_invisible_selector);
                    binding.include1.loginpsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    isVisible = false;

                } else {
                    binding.include1.showHidePassword.setImageResource(R.drawable.password_visible_selector);
                    binding.include1.loginpsw.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    isVisible = true;
                }
            }
        });
        binding.include1.emailSignInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.include1.loginid.getText().length() == 0)
                new MyToast(LoginActivity.this).showinfo("请输入工号/手机号");
                else if (binding.include1.loginpsw.getText().length() == 0)
                    new MyToast(LoginActivity.this).showinfo("请输入密码");
                else {
                    viewModel.loginInw(binding.include1.loginid.getText().toString().trim(),binding.include1.loginpsw.getText().toString().trim())
                    .observe(LoginActivity.this, new Observer<LiveDataWrapper<LoginInfo>>() {
                        @Override
                        public void onChanged(@Nullable LiveDataWrapper<LoginInfo> loginInfoLiveDataWrapper) {
                            switch (loginInfoLiveDataWrapper.status){
                                case LOADING:
                                    DialogUtils.waitingDialog(LoginActivity.this);
                                    break;
                                case SUCCESS:
                                    DialogUtils.dismiss(LoginActivity.this);
//                                    PreferenceManager.getInstance().setStaffInfo( new Gson().toJson(loginInfoLiveDataWrapper.data.getStaffResponses().get(0), StaffResponse.class));
//                                    saveResultAndReInit(binding.include1.loginid.getText().toString().trim(),binding.include1.loginpsw.getText().toString().trim());
//                                    goToMain();
                                    viewModel.getStaffInfo();
                                    break;
                                case ERROR:
                                    DialogUtils.dismiss(LoginActivity.this);
                                    binding.include1.errorNotice.setVisibility(View.VISIBLE);
                                    break;
                            }
                        }
                    });
                }
            }
        });
        //切换域名的操作，对MyDilog加上确认监听
        binding.include1.loginimgIc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDG = CreateDialog.editDialog(LoginActivity.this, preferenceManager.getLoginHost(), preferenceManager.getAPIHost());
                mDG.setOnConfirmListener(new MDialog.OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        restAppComponent();
                    }
                });
            }
        });
        binding.include1.errorNotice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.include1.errorNotice.setVisibility(View.INVISIBLE);
            }
        });
        //获取用户信息
        viewModel.staff.observe(this, new Observer<LiveDataWrapper<StaffListResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<StaffListResponse> staffListResponseLiveDataWrapper) {
                switch (staffListResponseLiveDataWrapper.status){
                    case LOADING:
                        DialogUtils.waitingDialog(LoginActivity.this);
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(LoginActivity.this);
                        PreferenceManager.getInstance().setStaffInfo( new Gson().toJson(staffListResponseLiveDataWrapper.data.getStaffResponses().get(0), StaffResponse.class));
                        saveResultAndReInit(binding.include1.loginid.getText().toString().trim(),binding.include1.loginpsw.getText().toString().trim());
//                                    restAppComponent();
                        goToMain();
                        break;
                    case ERROR:
                        DialogUtils.dismiss(LoginActivity.this);
                        binding.include1.errorNotice.setVisibility(View.VISIBLE);
                        break;
                }
            }
        });
    }

    private void restAppComponent(){
        DaggerAppComponent.builder().create((NewMainApplication) getApplication()).inject((NewMainApplication) getApplication());
    }

    public static void startAndClearTask(Context context) {
        Intent starter = new Intent(context, LoginActivity.class);
        starter.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(starter);
    }
    private void goToMain(){
        if ( !TextUtils.isEmpty(preferenceManager.getCurrentUserAccessToken())){
            restAppComponent();
            Intent mIntent = new Intent(this, MainActivity.class);
            startActivity(mIntent);
            finish();
        }
    }

}
